package com.itheima.reggie.common;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice(annotations = {RestController.class, Controller.class})
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R  handlerSQLConstraintException(SQLIntegrityConstraintViolationException exception){
        //日志打印错误信息
        log.info(exception.getMessage());
        //读取打印的错误信息判断是否是唯一约束异常
        String message = exception.getMessage();
        if (message.contains("Duplicate entry")){
            //对异常信息进行处理并返回用户名重复
            String name = message.split(" ")[2].replace("'", " ");
            return R.error(name+"已存在");
        }
        return R.error("数据异常!");
    }
}
